package com.meterreadingsys.activity;



import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.meterreadingsys.VO.UserVO;
import com.meterreadingsys.db.DBOpenHelper;

import com.meterreadingsys.db.UserInfoDB;
import com.meterreadingsys.httpserver.HttpClientServer;


import com.meterreadingsys.service.GPSService;
import com.meterreadingsys.util.GpsInfo;
import com.meterreadingsys.util.SharedPreferenceUtil;



import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;

import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

import android.provider.Settings;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

/**
 * 上下班考勤
 * @author king
 *
 */
public class CheckWorkActivity extends Activity{
	
	public EditText username;
	
	public EditText userpass;
	
	public Button shanban;
	
	public Button xiaban;
	
	public GpsInfo gps;
	
	public boolean b=false;
	
	//请求
	public static final String LOG="/Struts2/login!ckecklogin";
	
	public HttpClientServer server;
	
	public String respone="";
	
	public SQLiteDatabase sqldb;
	
	public UserInfoDB db;
	
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.checkwork);
		server=new HttpClientServer(this, LOG);
		username=(EditText)findViewById(R.id.editText1);
		userpass=(EditText)findViewById(R.id.editText2);
		shanban=(Button)findViewById(R.id.shangban);
		xiaban=(Button)findViewById(R.id.xiaban);
		
		DBOpenHelper helper=new DBOpenHelper(this);
		sqldb=helper.getWritableDatabase();
		db=new UserInfoDB(sqldb);
		//点击下班事件
		xiaban.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				//关闭服务
				Intent intent1=new Intent(CheckWorkActivity.this, GPSService.class);
				stopService(intent1);
				gps=new GpsInfo(CheckWorkActivity.this);
			    if(!gps.openGPSSettings()){

					Toast.makeText(CheckWorkActivity.this, "请开启GPS！", Toast.LENGTH_SHORT).show();
			        Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
			        startActivityForResult(intent,0); 
			    }
			  String name=username.getText().toString();
			  String pass=userpass.getText().toString();
			 boolean bbb= SharedPreferenceUtil.gotoWork(CheckWorkActivity.this, false);
			
				
			}
		});
		//点击上班事件
		shanban.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				gps=new GpsInfo(CheckWorkActivity.this);
			    if(!gps.openGPSSettings()){

					Toast.makeText(CheckWorkActivity.this, "请开启GPS！", Toast.LENGTH_SHORT).show();
			        Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
			        startActivityForResult(intent,0); 
			    }
				
				boolean bo=SharedPreferenceUtil.querygotoWork(CheckWorkActivity.this);
				
				if(bo){
					Toast.makeText(CheckWorkActivity.this, "今天已打过上班卡", Toast.LENGTH_SHORT)
		             .show();
					finish();
					return;
				}
				
				
				
				final LocationManager manager=gps.getLocationManager();
				 String provider = manager.getBestProvider(gps.getCriteria(), true); // 获取GPS信息
				  final Location location = manager.getLastKnownLocation(provider); // 通过GPS获取位置
			        updateToNewLocation(location);
			       
				 manager.requestLocationUpdates(provider, 0, 0, new LocationListener() {
					
					@Override
					public void onStatusChanged(String provider, int status, Bundle extras) {
						// TODO Auto-generated method stub
						
					}
					
					@Override
					public void onProviderEnabled(String provider) {
						
						
					}
					
					@Override
					public void onProviderDisabled(String provider) {
						
			             Location location = manager.getLastKnownLocation(provider); // 通过GPS获取位置
				        updateToNewLocation(location);
					}
					
					@Override
					public void onLocationChanged(Location location) {
						boolean bo=SharedPreferenceUtil.querygotoWork(CheckWorkActivity.this);
						if(!bo){
							System.out.println("上班更新地址");
							updateToNewLocation(location);
						}
						
						
					}
				});

				if(TextUtils.isEmpty(respone)||respone.equals("error")){
					 Toast.makeText(CheckWorkActivity.this, "网络连接失败", Toast.LENGTH_SHORT)
		             .show();
				}else{										
					List<ContentValues> list=new ArrayList<ContentValues>();											
						JSONArray json;						
						try {
							JSONObject jb=new JSONObject(respone);
							json = jb.getJSONArray("list");
							for(int i=0;i<json.length();i++){
								JSONObject js=json.getJSONObject(i);
								ContentValues value=new ContentValues();
								value.put("username", js.getString("name"));
								value.put("userpass", js.getString("pass"));
								value.put("useradds", js.getString("adds"));
								value.put("phone", js.getString("phone"));
								value.put("usernumber", js.getString("number"));
								list.add(value);
							}
							List<ContentValues> lists=new ArrayList<ContentValues>();
							JSONArray json1=jb.getJSONArray("lists");
							for(int i=0;i<json1.length();i++){
								JSONObject js=json1.getJSONObject(i);
								ContentValues value=new ContentValues();
								value.put("num", js.getString("number"));
								value.put("money", js.getString("money"));
								value.put("_name", js.getString("name"));
								lists.add(value);
							}
						boolean b=	db.insertAllUser(list);
						System.out.println(b);
						boolean bb=db.insert(lists);
						SharedPreferenceUtil.gotoWork(CheckWorkActivity.this, true);
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						;
						//启动系统服务
						 Intent intent=new Intent(CheckWorkActivity.this, GPSService.class);
					     startService(intent);
					final AlertDialog dialog1 =new AlertDialog.Builder(CheckWorkActivity.this)
			        .setTitle("提示信息")
			        .setIcon(R.drawable.ic_launcher)//设置Logo
			        .setMessage("上班打卡成功")
			        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
						   SharedPreferenceUtil.insertName(CheckWorkActivity.this, username.getText().toString());
						   SharedPreferenceUtil.gotoWork(CheckWorkActivity.this, true);
						   finish();
							
						}
					}).create();
					dialog1.show();
				}
			}
		});
	}
	
	public Double[] updateToNewLocation(Location location1) {

	      
        System.out.println("更新地址");
        if (location1 != null) {
              UserVO user=new UserVO();
              user.setName("上班打卡");
				user.setPass(userpass.getText().toString());
				user.setAltitude(location1.getLatitude());
				user.setLatitude(location1.getLongitude());
				respone=server.doLoginPost(user);
				
            return new Double[]{location1.getLatitude(),location1.getLongitude()};
           
        } else {
           System.out.println("无法获取");
        }
		return null;

    }

	@Override
	protected void onDestroy() {
		sqldb.close();
		super.onDestroy();
	}

}
